package com.meshnetics.gb.stack.core.apl.type;

import com.meshnetics.gb.type.impl.zcl.FixedBytesDataValue;

/**
 * Application device version.
 *
 * @author mmarkov
 */
public class DeviceVersion extends FixedBytesDataValue {
    /** Minimum allowed device version. */
    public static final byte MIN_VERSION = 0;

    /** Maximum allowed device version. */
    public static final byte MAX_VERSION = 15;

    /**
     * Constructs DeviceVersion from the given byte value.
     *
     * @param ver byte device version
     * @throws IllegalArgumentException if the given id is < 0 or > 15
     */
    public DeviceVersion(byte ver) {
        super(TypeDeviceVersion.TYPE, new byte[] { ver });

        if (isInvalid()) {
            throw new IllegalArgumentException("Invalid device version: " + ver);
        }
    }

    /**
     * Constructs DeviceVersion from the array of bytes (which should contain 1 element).
     * It's needed for its constructing from TypeDeviceVersion.createValue() method.
     *
     * @param type TypeDeviceVersion
     * @param value byte array with 1 element
     * @throws IllegalArgumentException if the given id is < 0 or > 15
     */
    protected DeviceVersion(TypeDeviceVersion type, byte[] value) {
        super(type, value);

        if (isInvalid()) {
            throw new IllegalArgumentException("Invalid device version: " + value[0]);
        }
    }

    /**
     * Returns true as DeviceVersion is within 0-15 range.
     *
     * @return true
     */
    protected boolean isUnsigned() {
        return true;
    }

    /**
     * Returns true if ver < 0 or > 15 and false otherwise.
     *
     * @return true if ver < 0 or > 15 and false otherwise
     */
    public boolean isInvalid() {
        return ((value[0] < MIN_VERSION) || (value[0] > MAX_VERSION));
    }

    /**
     * Returns version value as byte.
     *
     * @return version value as byte.
     */
    public byte getByteVersion() {
        return value[0];
    }
}
